<script setup lang="ts">
import { h, ref } from 'vue';
import { NButton } from 'naive-ui';
import { getRouteList } from '@/service/api';
import Table from '@/components/table/index.vue';
import type { FormItemProps, FormProps } from '@/components/form/props';
import Drawer from './modules/drawer.vue';
const drawerRef = ref<InstanceType<typeof Drawer>>();
const tableRef = ref<InstanceType<typeof Table>>();

defineOptions({
  name: 'SystemRoute'
});

const id = ref(0);

function sendMail(params: Api.System.Route) {
  id.value = params.id;
  drawerRef.value?.activate();
}

const columns = [
  {
    title: '角色名称',
    key: 'name'
  },
  {
    title: '拥有权限',
    key: 'permissions',
    render(row: Api.System.Route) {
      return row.permissions.map(item => item.name).join(',');
    }
  },
  {
    title: '创建时间',
    key: 'createTime'
  },
  {
    title: '操作',
    key: 'actions',
    align: 'center',
    width: 130,
    render(row: Api.System.Route) {
      return h('div', { class: 'flex justify-between' }, [
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            ghost: true,
            onClick: () => sendMail(row)
          },
          { default: () => '编辑' }
        ),
        h(
          NButton,
          { size: 'small', type: 'error', ghost: true, onClick: () => handleDelete([row.id]) },
          { default: () => '删除' }
        )
      ]);
    }
  }
];

const formItems: FormItemProps[] = [
  {
    label: '角色名称',
    path: 'name',
    component: 'input',
    componentProps: {
      placeholder: '请输入角色名称'
    },
    grid: {
      span: 6
    }
  }
];
const formConfig: FormProps = {
  formItems,
  labelPlacement: 'left',
  modelValue: {
    name: ''
  },
  rules: {},
  size: 'medium',
  labelWidth: 80,
  inline: true,
  formGrid: {
    span: 18
  }
};

// 刷新列表
function refreshList() {
  tableRef.value?.updateList();
}

// 批量删除
function batchDelete(params: any[]) {
  console.log(params);
}
// 新增
function handleAdd() {
  id.value = 0;
  drawerRef.value?.activate();
}
// 删除
function handleDelete(params: any[]) {
  console.log(params);
}
</script>

<template>
  <div>
    <Table
      ref="tableRef"
      :columns="columns"
      :api="getRouteList"
      :use-form="true"
      table-title="角色管理"
      :form-config="formConfig"
      @batch-delete="batchDelete"
      @add="handleAdd"
    />
    <Drawer ref="drawerRef" :route-id="id" @refresh-list="refreshList" />
  </div>
</template>

<style scoped></style>
